#!/bin/bash

PROGRAM=`basename $0`
export JS_USE_INDENT=true

while getopts ci:jo:rt:u: OPT
do
    case $OPT in
        "b" ) FLG_B="TRUE" ;;
        "c" ) FLG_C="TRUE" ;;
        "i" ) FLG_I="TRUE" ; VALUE_I="$OPTARG" ;;
        "j" ) FLG_J="TRUE" ;;
        "o" ) FLG_O="TRUE" ; VALUE_O="$OPTARG" ;;
        "r" ) FLG_R="TRUE" ;;
        "t" ) FLG_T="TRUE" ; VALUE_T="$OPTARG" ;;
        "u" ) FLG_U="TRUE" ; VALUE_U="$OPTARG" ;;
          * ) OPT_ERROR=1; break;;
    esac
done

# set imput file
if [ "$FLG_I" = "TRUE" ]; then
    INPUT=$VALUE_I
else
    OPT_ERROR=1
fi

if [ $OPT_ERROR ]; then
    echo "Usage: $PROGRAM [-j] [-r] [-i input_file] [-o output_file] [-t gentype] [-u use_func_list]" 1>&2
    exit 1
fi

# set html include option
if [ "$FLG_J" = "TRUE" ]; then
    export JS_GEN_HTML=false
else
    export JS_GEN_HTML=true
fi

# set output file
if [ "$FLG_O" = "TRUE" ]; then
    OUTPUT=$VALUE_O
fi

# set konohascript runtime include option
if [ "$FLG_R" = "TRUE" ]; then
    export JS_INCLUDE_RUNTIME=true
else
    export JS_INCLUDE_RUNTIME=false
fi

# set obfuscate option
if [ "$FLG_B" = "TRUE" ]; then
    export JS_USE_OBFUSCATE=true
else
    export JS_USE_OBFUSCATE=false
fi

# set compile error output option
if [ "$FLG_C" = "TRUE" ]; then
    export JS_ERROR_OUTPUT=true
else
    export JS_ERROR_OUTPUT=false
fi

# set gen type
if [ "$FLG_T" = "TRUE" ]; then
    if [ "$VALUE_T" = "worker" ]; then
        export JS_USE_WORKER=true
    else
        export JS_USE_WORKER=false
    fi
fi

# set unobfuscate functions
if [ "$FLG_U" = "TRUE" ]; then
    export JS_USE_FUNC_LIST="$VALUE_U"
fi

if [ "$FLG_I" = "TRUE" ]; then
    if [ "$FLG_O" = "TRUE" ]; then
#/usr/bin/gdb --arg /usr/local/bin/konohac --emit-js $INPUT > $OUTPUT
        /usr/local/bin/konohac --emit-js $INPUT > $OUTPUT
    else
#`/usr/bin/which konohac` --emit-js $INPUT
#/usr/bin/gdb --arg /usr/local/bin/konohac --emit-js $INPUT
        /usr/local/bin/konohac --emit-js $INPUT
    fi
fi

#if test $1 = "--test" ; then
#    export JS_GEN_HTML=false
#    INPUT=$2
#    OUTPUT=$3
#    `which konohac` --emit-js $INPUT > $OUTPUT
#else
#    if test $1 = "--gen-html" ; then
#        export JS_GEN_HTML=true
#        INPUT=$2
#        OUTPUT=$3
#    else
#        export JS_GEN_HTML=false
#        INPUT=$1
#        OUTPUT=$2
#    fi
#    NUM_EXPECTED_ARGS=1
#    if [ $# -lt $NUM_EXPECTED_ARGS ]; then
#        echo "example: $PROGRAM source.k target.js"
#        exit 1;
#    fi
#    if [ $# -lt 2 ]; then
#        `which konohac` --emit-js $INPUT
#    else
#        `which konohac` --emit-js $INPUT > $OUTPUT
#    fi
#fi
